package com.example.mybook.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mybook.R;
import com.example.mybook.biz.TcpClientbiz;

public class TcpActivity extends AppCompatActivity {
    private EditText mMsg;
    private Button mBtn_send;
    private TextView mTvContent;
    private TcpClientbiz mTcpclient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tcp);
        init();
        mTcpclient = new TcpClientbiz(this);
        mTcpclient.setOnMsgCommingListener(new TcpClientbiz.OnMsgCommingListener() {
            @Override
            public void onMsgComing(String msg) {
                appendMsgToContent(msg);
            }

            @Override
            public void onError(Exception ex) {
                ex.printStackTrace();
            }
        });
        mBtn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = mMsg.getText().toString();
                mMsg.setText("");
                if (TextUtils.isEmpty(msg)){
                    return;
                }else {
                    mTcpclient.sendMsg(msg);
                }
            }
        });
    }

    private void appendMsgToContent(String msg){
            mTvContent.append(msg+"\n");
    }

    private void init() {
        mMsg = findViewById(R.id.et_msg);
        mBtn_send = findViewById(R.id.btn_send);
        mTvContent = findViewById(R.id.tv_content);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTcpclient.onDestory();
    }
}
